package com.neu.questionnaireplus.controller;

import cn.hutool.crypto.digest.MD5;
import com.neu.questionnaireplus.entity.Answerer;
import com.neu.questionnaireplus.entity.HttpResponseEntity;
import com.neu.questionnaireplus.service.AnswererService;
import com.neu.questionnaireplus.service.MsmService;
import com.neu.questionnaireplus.utils.common.CommonUtils;
import com.neu.questionnaireplus.utils.constant.HttpStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Description: 使用swagger进行测试, url未使用rap2的，项目整合时再做修改
 * @Param:
 * @return:
 * @Author: ~FHX~ (:TSunS:)
 * @Date: 2022/10/30
 */
@RestController
@RequestMapping("/answerer")
@CrossOrigin
@Api("答者服务")
@Validated
public class AnswererController {

    @Autowired
    private AnswererService answererService;

    @Autowired
    private MsmService msmService;

    /**
     * @Description: map用来暂时存储短信验证码，key是手机号，value是验证码 ,ConcurrentHashMap保障并发安全
     * @Param:
     * @return:
     * @Author: ~FHX~ (:TSunS:)
     * @Date: 2022/11/2
     */
    private Map<String, String> loginmap = new ConcurrentHashMap<String, String>();
    private Map<String, String> registermap = new ConcurrentHashMap<String, String>();
    private Map<String, String> resetPwdmap = new ConcurrentHashMap<String, String>();

    @ApiOperation("注册答者时发送短信")
    @RequestMapping(value = "/registersmsAnswerer", method = RequestMethod.POST, headers = "Accept=application/json")
    public HttpResponseEntity registerSms(@RequestBody Map<String,Object> map){
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        try {
            String phone = map.get("phone").toString();
            String s = msmService.registerSend("86"+phone);
            registermap.put(phone,s);
            httpResponseEntity
                    .setCode(HttpStatus.SUCCESS)
                    .setData(s)
                    .setMessage("success");
        }catch (Exception e){
            httpResponseEntity
                    .setCode(HttpStatus.ERROR)
                    .setData(null)
                    .setMessage(e.getMessage());
        }finally {
            return httpResponseEntity;
        }
    }

    @ApiOperation("答者找回密码时发送短信")
    @RequestMapping(value = "/findPwdSmsAnswerer", method = RequestMethod.POST, headers = "Accept=application/json")
    public HttpResponseEntity findPwdSms(@RequestBody Map<String,Object> map){
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        try{
            String phone = map.get("phone").toString();
            String s = msmService.resetPwdSend("86"+phone);
            resetPwdmap.put(phone,s);
            httpResponseEntity
                    .setCode(HttpStatus.SUCCESS)
                    .setData(s)
                    .setMessage("success");
        }catch (Exception e){
            httpResponseEntity
                    .setCode(HttpStatus.ERROR)
                    .setData(null)
                    .setMessage(e.getMessage());
        }finally {
            return httpResponseEntity;
        }
    }

    @ApiOperation("用户管理答者时创建答者")
    @RequestMapping(value = "/createAnswerer", method = RequestMethod.POST, headers = "Accept=application/json")
    public HttpResponseEntity createAnswerer(@RequestBody Map<String, Object> map){
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        try {
            Answerer answerer = new Answerer();
            answerer
                .setDelFlag(0)
                .setStatus(0)
                .setCreatedDate(CommonUtils.getDateByDateString(CommonUtils.getFormatDateTimeNow()))
                .setId(CommonUtils.getUUID())
                .setPassword(MD5.create().digestHex(map.get("password").toString()))
                .setUsername(map.get("username").toString())
                .setSecurityQuestionAnswer(map.get("securityQuestionAnswer").toString())
                .setSecurityQuestionContext(map.get("securityQuestionContext").toString())
                .setTelnumber(map.get("telnumber").toString())
                .setRole(0);
            answererService.createAnswerer(answerer);
            httpResponseEntity
                .setCode(HttpStatus.SUCCESS)
                .setData(answerer)
                .setMessage("success");
        }catch (Exception e){
            httpResponseEntity
                .setCode(HttpStatus.ERROR)
                .setData(null)
                .setMessage(e.getMessage());
        }finally {
            return httpResponseEntity;
        }
    }

    /**
     * @Description:  注意一个方法中的参数只能有一个RequestBody
     * @Param: [answerer, str]
     * @return: com.neu.questionnaireplus.entity.HttpResponseEntity
     * @Author: ~FHX~ (:TSunS:)
     * @Date: 2022/11/2
     */
    @ApiOperation("发送短信后注册")
    @RequestMapping(value = "/registerAnswerer", method = RequestMethod.POST, headers = "Accept=application/json")
    public HttpResponseEntity registerAnswerer(@RequestBody Map<String, Object> map){
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        try {
            String telnumber = map.get("telnumber").toString();
            boolean b = answererService.checkRegisterStr(telnumber, map.get("str").toString(),registermap.get(telnumber));
            if (b){
                Answerer answerer1 = new Answerer();
                answerer1
                        .setDelFlag(0)
                        .setStatus(0)
                        .setCreatedDate(CommonUtils.getDateByDateString(CommonUtils.getFormatDateTimeNow()))
                        .setId(CommonUtils.getUUID())
                        .setPassword(MD5.create().digestHex(map.get("password").toString()))
                        .setUsername(map.get("username").toString())
                        .setSecurityQuestionAnswer(map.get("securityQuestionAnswer").toString())
                        .setSecurityQuestionContext(map.get("securityQuestionContext").toString())
                        .setTelnumber(telnumber)
                        .setRole(0);
                answererService.insertAnswerer(answerer1);
                httpResponseEntity
                        .setCode(HttpStatus.SUCCESS)
                        .setData(answerer1)
                        .setMessage("success");
            }else {
                httpResponseEntity
                        .setCode(HttpStatus.ERROR)
                        .setData(null)
                        .setMessage("验证码错误");
            }
        }catch (Exception e){
            httpResponseEntity
                    .setCode(HttpStatus.ERROR)
                    .setData(null)
                    .setMessage(e.getMessage());
        }finally {
            return httpResponseEntity;
        }
    }

     @ApiOperation("通过密码登录")
     @RequestMapping(value = "/loginByPwdAnswerer", method = RequestMethod.POST, headers = "Accept=application/json")
     public HttpResponseEntity loginByPwd(@RequestBody Map<String,Object> map){
        HttpResponseEntity responseEntity = new HttpResponseEntity();
        try {
            String username = map.get("username").toString();
            String password = map.get("password").toString();
            boolean b = answererService.loginByPassword(username, MD5.create().digestHex(password));
            Answerer answerer = answererService.queryAnswererByUsername(username);
            if (b){
                responseEntity
                        .setCode(HttpStatus.SUCCESS)
                        .setData(answerer)
                        .setMessage("success");
            }else {
                responseEntity
                        .setCode(HttpStatus.ERROR)
                        .setData(null)
                        .setMessage("用户名或密码错误");
            }
        }catch (Exception e){
            responseEntity
                    .setCode(HttpStatus.ERROR)
                    .setData(null)
                    .setMessage(e.getMessage());
        }finally {
            return responseEntity;
        }
    }



    @ApiOperation("通过短信验证码登录")
    @RequestMapping(value = "/loginBySmsAnswerer", method = RequestMethod.POST, headers = "Accept=application/json")
    public HttpResponseEntity loginBySms(@RequestBody Map<String,Object> map){
        HttpResponseEntity responseEntity = new HttpResponseEntity();
        try {
            String phone = map.get("phone").toString();
            String str = map.get("str").toString();
            boolean b = answererService.loginByPhone(phone, str, loginmap.get(phone));
            Answerer answerer = answererService.queryAnswererByPhone(phone);
            if (b){
                responseEntity
                        .setCode(HttpStatus.SUCCESS)
                        .setData(answerer)
                        .setMessage("success");
            }else {
                responseEntity
                        .setCode(HttpStatus.ERROR)
                        .setData(null)
                        .setMessage("手机号或短信验证码错误");
            }
        }catch (Exception e){
            responseEntity
                    .setCode(HttpStatus.ERROR)
                    .setData(null)
                    .setMessage(e.getMessage());
        }finally {
            return responseEntity;
        }
    }

    @ApiOperation("通过密保找回密码（验证密保）")
    @RequestMapping(value = "/checkSecAnswerer", method = RequestMethod.POST, headers = "Accept=application/json")
    public HttpResponseEntity checkSec(@RequestBody Map<String,Object> map){
        HttpResponseEntity responseEntity = new HttpResponseEntity();
        try {
            String securityQuestionAnswer = map.get("securityQuestionAnswer").toString();
            String username = map.get("username").toString();
            boolean b = answererService.checkSecurityQuestion(username, securityQuestionAnswer);
            if (b){
                responseEntity
                        .setCode(HttpStatus.SUCCESS)
                        .setData(b)
                        .setMessage("success");
            }else {
                responseEntity
                        .setCode(HttpStatus.ERROR)
                        .setData(null)
                        .setMessage("密保或用户名错误");
            }
        }catch (Exception e){
            responseEntity
                    .setCode(HttpStatus.ERROR)
                    .setData(null)
                    .setMessage(e.getMessage());
        }finally {
            return responseEntity;
        }
    }

    @ApiOperation("找回密码（重置密码）")
    @RequestMapping(value = "/resetPwdAnswerer", method = RequestMethod.POST, headers = "Accept=application/json")
    public HttpResponseEntity resetPwd(@RequestBody Map<String,Object> map){
        HttpResponseEntity responseEntity = new HttpResponseEntity();
        try {
            String username = map.get("username").toString();
            Answerer answerer = answererService.queryAnswererByUsername(username);
            if (answerer != null){
                String newpassword = map.get("newpassword").toString();
                answerer.setPassword(MD5.create().digestHex(newpassword));
                boolean b = answererService.updateAnswerer(answerer);
                if (b){
                    responseEntity
                            .setCode(HttpStatus.SUCCESS)
                            .setData(answerer)
                            .setMessage("success");
                }else {
                    responseEntity
                            .setCode(HttpStatus.ERROR)
                            .setData(null)
                            .setMessage("修改失败");
                }
            }else {
                responseEntity
                        .setCode(HttpStatus.ERROR)
                        .setData(null)
                        .setMessage("答者不存在");
            }
        }catch (Exception e){
            responseEntity
                    .setCode(HttpStatus.ERROR)
                    .setData(null)
                    .setMessage(e.getMessage());
        }finally {
            return responseEntity;
        }
    }

    @ApiOperation("改变答者状态")
    @RequestMapping(value = "/changeAnswererStatus", method = RequestMethod.POST, headers = "Accept=application/json")
    public HttpResponseEntity changeAnswererStatus(@RequestBody Map<String, Object> map) {
        HttpResponseEntity responseEntity = new HttpResponseEntity();
        try {
            String username = map.get("username").toString();
            Answerer answerer = answererService.queryAnswererByUsername(username);
            if (answerer != null) {
                boolean b = answerer.getStatus() == 1 ? answererService.freeAnswerer(answerer.getId()) : answererService.forbiddenAnswerer(answerer.getId()) ;
                if (b) {
                    responseEntity
                        .setCode(HttpStatus.SUCCESS)
                        .setData(answerer)
                        .setMessage("success");
                } else {
                    responseEntity
                        .setCode(HttpStatus.ERROR)
                        .setData(null)
                        .setMessage("答者状态改变失败");
                }
            } else {
                responseEntity
                    .setCode(HttpStatus.ERROR)
                    .setData(null)
                    .setMessage("答者不存在");
            }
        } catch (Exception e) {
            responseEntity
                .setCode(HttpStatus.ERROR)
                .setData(null)
                .setMessage(e.getMessage());
        } finally {
            return responseEntity;
        }
    }

    @ApiOperation("修改答者信息")
    @RequestMapping(value = "/updateAnswerer", method = RequestMethod.POST, headers = "Accept=application/json")
    public HttpResponseEntity updateAnswerer(@RequestBody Map<String,Object> map){
        HttpResponseEntity responseEntity = new HttpResponseEntity();
        try {
            String id = map.get("id").toString();
            Answerer answerer = answererService.queryAnswererByID(id);
            if (answerer != null){
                String username = map.get("username").toString();
                String telnumber = map.get("telnumber").toString();
                String securityQuestionAnswer = map.get("securityQuestionAnswer").toString();
                String securityQuestionContext = map.get("securityQuestionContext").toString();
                answerer
                        .setUsername(username)
                        .setTelnumber(telnumber)
                        .setSecurityQuestionAnswer(securityQuestionAnswer)
                        .setSecurityQuestionContext(securityQuestionContext);
                boolean b = answererService.updateAnswerer(answerer);
                if (b){
                    responseEntity
                            .setCode(HttpStatus.SUCCESS)
                            .setData(telnumber)
                            .setMessage("success");
                }else {
                    responseEntity
                            .setCode(HttpStatus.ERROR)
                            .setData(null)
                            .setMessage("修改失败");
                }
            }else {
                responseEntity
                        .setCode(HttpStatus.ERROR)
                        .setData(null)
                        .setMessage("用户不存在");
            }
        }catch (Exception e){
            responseEntity
                    .setCode(HttpStatus.ERROR)
                    .setData(null)
                    .setMessage(e.getMessage());
        }finally {
            return responseEntity;

        }
    }

    @ApiOperation("删除答者（伪删除）")
    @RequestMapping(value = "/deleteAnswerer", method = RequestMethod.POST, headers = "Accept=application/json")
    public HttpResponseEntity deleteAnswerer(@RequestBody Map<String,Object> map){
        HttpResponseEntity responseEntity = new HttpResponseEntity();
        try {
            String username = map.get("username").toString();
            Answerer answerer = answererService.queryAnswererByUsername(username);
            if (answerer != null){
                boolean b = answererService.deleteAnswererInfo(answerer);
                if (b){
                    responseEntity
                            .setCode(HttpStatus.SUCCESS)
                            .setData(answerer)
                            .setMessage("success");
                }else {
                    responseEntity
                            .setCode(HttpStatus.ERROR)
                            .setData(null)
                            .setMessage("答者删除失败");
                }
            }else {
                responseEntity
                        .setCode(HttpStatus.ERROR)
                        .setData(null)
                        .setMessage("答者不存在");
            }
        }catch (Exception e){
            responseEntity
                    .setCode(HttpStatus.ERROR)
                    .setData(null)
                    .setMessage(e.getMessage());
        }finally {
            return responseEntity;
        }
    }


    @ApiOperation("展示所有未被删除的答者")
    @RequestMapping(value = "/showAnswerer", method = RequestMethod.POST, headers = "Accept=application/json")
    public HttpResponseEntity showAllAnswerers() {
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        try {
            List<Answerer> answerers = answererService.queryExistAnswerer();
            httpResponseEntity
                    .setCode(HttpStatus.SUCCESS)
                    .setData(answerers)
                    .setMessage("success");
        } catch (Exception e) {
            httpResponseEntity
                    .setCode(HttpStatus.ERROR)
                    .setData(null)
                    .setMessage(e.getMessage());
        } finally {
            return httpResponseEntity;
        }
    }

    @ApiOperation("模糊查询所有未被删除的答者")
    @RequestMapping(value = "/showQueryAnswerer", method = RequestMethod.POST, headers = "Accept=application/json")
    public HttpResponseEntity showQueryAnswerers(@RequestBody Map<String,Object> map) {
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        try {
            String queryStr = map.get("queryStr").toString();
            List<Answerer> answerers = answererService.queryAnswererByName(queryStr);
            httpResponseEntity
                    .setCode(HttpStatus.SUCCESS)
                    .setData(answerers)
                    .setMessage("success");
        } catch (Exception e) {
            httpResponseEntity
                    .setCode(HttpStatus.ERROR)
                    .setData(null)
                    .setMessage(e.getMessage());
        } finally {
            return httpResponseEntity;
        }
    }

    @ApiOperation("将答者加入群组")
    @RequestMapping(value = "/insertAnswererToGroup", method = RequestMethod.POST, headers = "Accept=application/json")
    public HttpResponseEntity insertAnswererToGroup(@RequestBody Map<String,Object> map) {
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        try {
            List<String> list = (List<String>) map.get("answererNameArray");
            String groupName = map.get("groupName").toString();
            for (String answerername : list){
                answererService.insertAnswererToGroup(groupName,answerername);
            }
            httpResponseEntity
                .setCode(HttpStatus.SUCCESS)
                .setData(null)
                .setMessage("success");
        } catch (Exception e) {
            httpResponseEntity
                .setCode(HttpStatus.ERROR)
                .setData(null)
                .setMessage(e.getMessage());
        } finally {
            return httpResponseEntity;
        }
    }

    @ApiOperation("批量导入答者")
    @PostMapping(value = "/importFileToAnswerers")
    public HttpResponseEntity importFileToAnswerers(@RequestParam("file") MultipartFile file ) {
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        try {
            List<Answerer> answerers = answererService.importFileToAnswerers(file);
            httpResponseEntity
                .setCode(HttpStatus.SUCCESS)
                .setData(answerers)
                .setMessage("success");
        } catch (Exception e) {
            httpResponseEntity
                .setCode(HttpStatus.ERROR)
                .setData(null)
                .setMessage(e.getMessage());
        } finally {
            return httpResponseEntity;
        }
    }

}
